
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link href='/css/styles.css' rel='stylesheet' type='text/css' />
    <link href='/images/favicon.png' rel='shortcut icon' />
    <script src='/js/jquery.min.1.4.js'></script>
    <script src='/js/app.js'></script>
    <meta content='width=device-width, minimum-scale=1.0, maximum-scale=1.0' name='viewport' />
    <title>Redis中文资料站</title>
	<meta http-equiv="description" content="redis中文资料站，下载安装redis，查找redis常用命令（commands），选择适合的redis客户端方式，配置redis主从（master-slave），阅读redis官方文档，社区里了解更多redis信息，提交redis的bug。" />
  </head>
  <body class=''>
    <script src='/js/head.js'></script>
    <div class='text'>
      <article id='topic'>
        <h1>Partitioning: how to split data among multiple Redis instances.</h1>
        
        <p>Partitioning is the process of splitting your data into multiple Redis instances, so that every instance will only contain a subset of your keys. The first part of this document will introduce you to the concept of partitioning, the second part will show you the alternatives for Redis partitioning.</p>
        
        <h2>Why partitioning is useful</h2>
        
        <p>Partitioning in Redis serves two main goals:</p>
        
        <ul>
        <li>It allows for much larger databases, using the sum of the memory of many computers. Without partitioning you are limited to the amount of memory a single computer can support.</li>
        <li>It allows to scale the computational power to multiple cores and multiple computers, and the network bandwidth to multiple computers and network adapters.</li>
        </ul>
        
        <h2>Partitioning basics</h2>
        
        <p>There are different partitioning criteria. Imagine we have four Redis instances <strong>R0</strong>, <strong>R1</strong>, <strong>R2</strong>, <strong>R3</strong>, and many keys representing users like <code>user:1</code>, <code>user:2</code>, ... and so forth, we can find different ways to select in which instance we store a given key. In other words there are <em>different systems to map</em> a given key to a given Redis server.</p>
        
        <p>One of the simplest way to perform partitioning is called <strong>range partitioning</strong>, and is accomplished by mapping ranges of objects into specific Redis instances. For example I could say, users from ID 0 to ID 10000 will go into instance <strong>R0</strong>, while users form ID 10001 to ID 20000 will go into instance <strong>R1</strong> and so forth.</p>
        
        <p>This systems works and is actually used in practice, however it has the disadvantage that there is to take a table mapping ranges to instances. This table needs to be managed and we need a table for every kind of object we have. Usually with Redis it is not a good idea.</p>
        
        <p>An alternative to to range partitioning is <strong>hash partitioning</strong>. This scheme works with any key, no need for a key in the form <code>object_name:&lt;id&gt;</code> as is as simple as this:</p>
        
        <ul>
        <li>Take the key name and use an hash function to turn it into a number. For instance I could use the <code>crc32</code> hash function. So if the key is <code>foobar</code> I do <code>crc32(foobar)</code> that will output something like 93024922.</li>
        <li>I use a modulo operation with this number in order to turn it into a number between 0 and 3, so that I can map this number to one of the four Redis instances I&#39;ve. So <code>93024922 modulo 4</code> equals 2, so I know my key <code>foobar</code> should be stored into the <strong>R2</strong> instance. <em>Note: the modulo operation is just the rest of the division, usually it is implemented by the <code>%</code> operator in many programming languages.</em></li>
        </ul>
        
        <p>There are many other ways to perform partitioning, but with this two examples you should get the idea. One advanced form of hash partitioning is called <strong>consistent hashing</strong> and is implemented by a few Redis clients and proxies.</p>
        
        <h2>Different implementations of partitioning</h2>
        
        <p>Partitioning can be responsibility of different parts of a software stack.</p>
        
        <ul>
        <li><strong>Client side partitioning</strong> means that the clients directly select the right node where to write or read a given key. Many Redis clients implement client side partitioning.</li>
        <li><strong>Proxy assisted partitioning</strong> means that our clients send requests to a proxy that is able to speak the Redis protocol, instead of sending requests directly to the right Redis instance. The proxy will make sure to forward our request to the right Redis instance accordingly to the configured partitioning schema, and will send the replies back to the client. The Redis and Memcached proxy <a href="https://github.com/twitter/twemproxy">Twemproxy</a> implements proxy assisted partitioning.</li>
        <li><strong>Query routing</strong> means that you can send your query to a random instance, and the instance will make sure to forward your query to the right node. Redis Cluster implements an hybrid form of query routing, with the help of the client (the request is not directly forwarded from a Redis instance to another, but the client gets <em>redirected</em> to the right node).</li>
        </ul>
        
        <h2>Disadvantages of partitioning</h2>
        
        <p>Some features of Redis don&#39;t play very well with partitioning:</p>
        
        <ul>
        <li>Operations involving multiple keys are usually not supported. For instance you can&#39;t perform the intersection between two sets if they are stored in keys that are mapped to different Redis instances (actually there are ways to do this, but not directly).</li>
        <li>Redis transactions involving multiple keys can not be used.</li>
        <li>The partitioning granuliary is the key, so it is not possible to shard a dataset with a single huge key like a very big sorted set.</li>
        <li>When partitioning is used, data handling is more complex, for instance you have to handle multiple RDB / AOF files, and to make a backup of your data you need to aggregate the persistence files from multiple instances and hosts.</li>
        <li>Adding and removing capacity can be complex. For instance Redis Cluster plans to support mostly transparent rebalancing of data with the ability to add and remove nodes at runtime, but other systems like client side partitioning and proxies don&#39;t support this feature. However a technique called <em>Presharding</em> helps in this regard.</li>
        </ul>
        
        <h2>Data store or cache?</h2>
        
        <p>Partitioning when using Redis ad a data store or cache is conceptually the same, however there is a huge difference. While when Redis is used as a data store you need to be sure that a given key always maps to the same instance, when Redis is used as a cache if a given node is unavailable it is not a big problem if we start using a different node, altering the key-instance map as we wish to improve the <em>availability</em> of the system (that is, the ability of the system to reply to our queries).</p>
        
        <p>Consistent hashing implementations are often able to switch to other nodes if the preferred node for a given key is not available. Similarly if you add a new node, part of the new keys will start to be stored on the new node.</p>
        
        <p>The main concept here is the following:</p>
        
        <ul>
        <li>If Redis is used as a cache <strong>scaling up and down</strong> using consistent hashing is easy.</li>
        <li>If Redis is used as a store, <strong>we need to take the map between keys and nodes fixed, and a fixed number of nodes</strong>. Otherwise we need a system that is able to rebalance keys between nodes when we add or remove nodes, and currently only Redis Cluster is able to do this, but Redis Cluster is not production ready.</li>
        </ul>
        
        <h2>Presharding</h2>
        
        <p>We learned that a problem with partitioning is that, unless we are using Redis as a cache, to add and remove nodes can be tricky, and it is much simpler to use a fixed keys-instances map.</p>
        
        <p>However the data storage needs may vary over the time. Today I can live with 10 Redis nodes (instances), but tomorrow I may need 50 nodes.</p>
        
        <p>Since Redis is extremely small footprint and lightweight (a spare instance uses 1 MB of memory), a simple approach to this problem is to start with a lot of instances since the start. Even if you start with just one server, you can decide to live in a distributed world since your first day, and run multiple Redis instances in your single server, using partitioning.</p>
        
        <p>And you can select this number of instances to be quite big since the start. For example, 32 or 64 instances could do the trick for most users, and will provide enough room for growth.</p>
        
        <p>In this way as your data storage needs increase and you need more Redis servers, what to do is to simply move instances from one server to another. Once you add the first additional server, you will need to move half of the Redis instances from the first server to the second, and so forth.</p>
        
        <p>Using Redis replication you will likely be able to do the move with minimal or no downtime for your users:</p>
        
        <ul>
        <li>Start empty instances in your new server.</li>
        <li>Move data configuring these new instances as slaves for your source instances.</li>
        <li>Stop your clients.</li>
        <li>Update the configuration of the moved instances with the new server IP address.</li>
        <li>Send the <code>SLAVEOF NO ONE</code> command to the slaves in the new server.</li>
        <li>Restart your clients with the new updated configuration.</li>
        <li>Finally shut down the no longer used instances in the old server.</li>
        </ul>
        
        <h1>Implementations of Redis partitioning</h1>
        
        <p>So far we covered Redis partitioning in theory, but what about practice? What system should you use?</p>
        
        <h2>Redis Cluster</h2>
        
        <p>Unfortunately Redis Cluster is currently not production ready, however you can get more information about it <a href="/topics/cluster-spec.html">reading the specification</a> or checking the partial implementation in the <code>unstable</code> branch of the Redis GitHub repositoriy.</p>
        
        <p>Once Redis Cluster will be available, and if a Redis Cluster complaint client is available for your language, Redis Cluster will be the de facto standard for Redis partitioning.</p>
        
        <p>Redis Cluster is a mix between <em>query routing</em> and <em>client side partitioning</em>.</p>
        
        <h2>Twemproxy</h2>
        
        <p><a href="https://github.com/twitter/twemproxy">Twemproxy is a proxy developed at Twitter</a> for the Memcached ASCII and the Redis protocol. It is single threaded, it is written in C, and is extremely fast. It is open source software released under the terms of the Apache 2.0 license.</p>
        
        <p>Twemproxy supports automatic partitioning among multiple Redis instances, with optional node ejection if a node is not available (this will change the keys-instances map, so you should use this feature only if you are using Redis as a cache).</p>
        
        <p>It is <em>not</em> a single point of failure since you can start multiple proxies and instruct your clients to connect to the first that accepts the connection.</p>
        
        <p>Basically Twemproxy is an intermediate layer between clients and Redis instances, that will reliably handle partitioning for us with minimal additional complexities. Currently it is the <strong>suggested way to handle partitioning with Redis</strong>.</p>
        
        <p>You can read more about Twemproxy <a href="http://antirez.com/news/44">in this antirez blog post</a>.</p>
        
        <h2>Clients supporting consistent hashing</h2>
        
        <p>An alternative to Twemproxy is to use a client that implements client side partitioning via consistent hashing or other similar algorithms. There are multiple Redis clients with support for consistent hashing, notably <a href="https://github.com/redis/redis-rb">Redis-rb</a> and <a href="https://github.com/nrk/predis">Predis</a>.</p>
        
        <p>Please check the <a href="http://redis.io/clients">full list of Redis clients</a> to check if there is a mature client with consistent hashing implementation for your language.</p>
      </article>
    </div>
    <script src='/js/foot.js'></script>
  </body>
</html>
